<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="入住编号" prop="numberId">
          <el-input
            v-model="queryParams.numberId"
            placeholder="请输入入住编号"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <!-- <el-form-item label="参数键名" prop="configKey">
          <el-input
            v-model="queryParams.configKey"
            placeholder="请输入参数键名"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="系统内置" prop="configType">
          <el-select v-model="queryParams.configType" placeholder="系统内置" clearable>
            <el-option
              v-for="dict in dict.type.sys_yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="dateRange"
            style="width: 240px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <!-- <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button> -->
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:config:add']"
          >新增</el-button>
          <!-- <el-button
            type="success"
            
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:config:edit']"
          >修改</el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:config:remove']"
          >删除</el-button> -->
        </el-form-item>
      </el-form>
  
      <!-- <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:config:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:config:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:config:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['system:config:export']"
          >导出</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-refresh"
            size="mini"
            @click="handleRefreshCache"
            v-hasPermi="['system:config:remove']"
          >刷新缓存</el-button>
        </el-col> 
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row> -->
  
      <el-table v-loading="loading" :data="configList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号"  width="55" align="center" prop="id" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <!-- 计算序号 -->
            {{ (queryParams.pageNum - 1) * queryParams.pageSize+ scope.$index + 1  }}
          </template>
        </el-table-column>
        <el-table-column label="入住编号"  align="center" prop="numberId"  width="150"/>
        <el-table-column label="姓名" align="center" prop="checkinName" :show-overflow-tooltip="true" />
        <el-table-column label="手机号" align="center" prop="checkinPhone" :show-overflow-tooltip="true" />
        <el-table-column label="房间编号" align="center" prop="roomId" :show-overflow-tooltip="true" />
        <el-table-column label="房间类型" align="center" prop="checkinRoom" :show-overflow-tooltip="true" />
        <el-table-column label="入住天数" align="center" prop="inDays" :show-overflow-tooltip="true" />
        <el-table-column label="支付金额" align="center" prop="checkinPrice" :show-overflow-tooltip="true"  />
        <el-table-column label="支付方式" align="center" prop="checkinType" :show-overflow-tooltip="true"  />
        <el-table-column label="押金" align="center" prop="checkinDeposit" :show-overflow-tooltip="true" />
        <el-table-column label="入住时间" align="center" prop="checkinTime" width="150">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.checkinTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="退房时间" align="center" prop="checkinDate" width="150">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.checkinDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="120" fixed="right" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-s-claim"
              @click="handleContinueLiving(scope.row)"
              v-hasPermi="['system:checkin:update']"
            >续住</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-folder-delete"
              @click="handleCheckOut(scope.row)"
              v-hasPermi="['system:config:remove']"
            >退房</el-button>
            <el-button
            size="mini"
            type="text"
            icon="el-icon-s-claim"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:checkin:update']"
          >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-folder-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:checkin:delete']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
  
      <!-- 添加或修改参数配置对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="460px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="姓名" prop="checkinName">
            <el-input v-model="form.checkinName" placeholder="请输入姓名" :disabled="isContinueLiving||isCheckOut"/>
          </el-form-item>
          <el-form-item label="手机号" prop="checkinPhone">
            <el-input v-model="form.checkinPhone" placeholder="请输入手机号":disabled="isContinueLiving||isCheckOut" />
          </el-form-item>
          <el-form-item label="押金" prop="checkinDeposit">
            <el-input v-model="form.checkinDeposit" placeholder="请输入押金" disabled/>
          </el-form-item>
          <!-- <el-form-item label="客房编号" prop="roomId">
              <el-input v-model="form.roomId" placeholder="请输入客房编号" />
            </el-form-item>
          <el-form-item label="入住房间" prop="checkinRoom">
            <el-input v-model="form.checkinRoom" placeholder="请输入入住房间" />
          </el-form-item>
          <el-form-item label="支付金额" prop="checkinPrice">
            <el-input v-model="form.checkinPrice" placeholder="请输入支付金额" />
          </el-form-item> -->
          <el-form-item label="房间编号" prop="roomId">
            <el-select v-model="form.roomId" placeholder="请选择房间编号" style="width: 340px" :disabled="isContinueLiving||isCheckOut" @change="handleRoomIdChange">
              <el-option
                v-for="item in roomIdOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="房间类型" prop="checkinRoom">
            <el-select v-model="form.checkinRoom" placeholder="请选择房间类型" style="width: 340px" disabled>
              <el-option
                v-for="item in checkinRoomOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="入住天数" prop="inDays">
            <!-- <el-input v-model="form.inDays" placeholder="请输入入住天数"  @input="calculateDeposit" /> -->
            <el-input-number v-model="form.inDays" :min="(indaysMinNumber&&isContinueLiving)?Number(indaysMinNumber):1" :max="(indaysMaxNumber&&isCheckOut)?Number(indaysMaxNumber):Infinity" style="width: 340px" placeholder="请输入入住天数"  @input="calculateDeposit"/>
          </el-form-item>
          <el-form-item label="支付金额" prop="checkinPrice">
            <el-input v-model="form.checkinPrice" placeholder="请输入支付金额" disabled />
          </el-form-item>
          <el-form-item label="支付方式" prop="checkinType" v-if="!isContinueLiving&&!isCheckOut">
            <!-- <el-input v-model="form.checkinType" placeholder="请输入支付方式" /> -->
            <el-select v-model="form.checkinType" placeholder="请选择支付方式" style="width: 340px">
            <el-option
              v-for="item in checkinTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
          </el-form-item>
          <!-- <el-form-item label="入住时间" prop="checkinTime">
            <el-input v-model="form.checkinTime" placeholder="请输入入住时间" />
          </el-form-item> -->
          <el-form-item label="入住时间" prop="checkinTime" v-if="!isContinueLiving&&!isCheckOut" >
            <el-date-picker
              v-model="form.checkinTime"
              style="width: 340px"
              type="datetime"
              start-placeholder="开始日期"
              :disabled="isContinueLiving"
              :default-time="['00:00:00']"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="结算金额" prop="CheckOutSettlement" v-if="isCheckOut" >
            <el-input v-model="form.CheckOutSettlement" placeholder="请输入退房结算金额" />
          </el-form-item>
          <el-form-item label="退房明细" prop="checkOutDetails" v-if="isCheckOut">
            <el-input v-model="form.checkOutDetails"  type="textarea" :rows="2" placeholder="请输入退房明细" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { listCheckIn, getCheckInKey,  addCheckIn, updateCheckIn,updateContinueLiving,updateCheckingOut, delCheckIn,refreshCache } from "@/api/system/checkin";
  import { listGuestRoom as roomInfoListConfig} from "@/api/system/guestRoom";

  export default {
    name: "Config",
    dicts: ['sys_yes_no'],
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 参数表格数据
        configList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 日期范围
        dateRange: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          configName: undefined,
          configKey: undefined,
          configType: undefined
        },
        // 表单参数
        form: {},
        // 表单校验
      rules: {
        checkinName: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        checkinPhone: [
          { required: true, message: "电话不能为空", trigger: "blur" }
        ],
        roomId: [
          { required: true, message: "房间编号不能为空", trigger: "blur" }
        ],
        inDays: [
          { required: true, message: "入住天数不能为空", trigger: "blur" }
        ],
        checkinTime: [
          { required: true, message: "房间类型不能为空", trigger: "blur" }
        ]
      },
      roomIdOptions: [
        // { value: '101', label: '101号房间' },
        // { value: '102', label: '102号房间' },
        // { value: '103', label: '103号房间' }
      ],
      checkinRoomOptions: [
        // { value: 'single', label: '单人间' },
        // { value: 'double', label: '双人间' },
        // { value: 'suite', label: '套房' }
      ],
      roomInfoMap: {
        // '101': { houseType: 'single', roomPrice: 200 },
        // '102': { houseType: 'double', roomPrice: 300 },
        // '103': { houseType: 'suite', roomPrice: 500 }
      },
      checkinTypeOptions: [
        { value: '微信', label: '微信' },
        { value: '支付宝', label: '支付宝' },
        { value: '网银', label: '网银' },
        { value: '现金', label: '现金' }
      ],
      indaysMinNumber:0,
      indaysMaxNumber:0,
      currentMonery:0,
      isEdit:false,
      isContinueLiving:false,
      isCheckOut:false,
      };
    },
    created() {
      this.getList();
      this.getRoomInfoList();
    },
    methods: {
      /** 查询参数列表 */
      getList() {
        this.loading = true;
        listCheckIn(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
            this.configList = response.rows;
            this.total = response.total;
            this.loading = false;
          }
        );
      },
      //客房信息
      getRoomInfoList() {
        this.loading = true;
        roomInfoListConfig(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          if (response.rows.length > 0) {
            const roomIdOptions = [];
            const checkinRoomSet = new Set();
            const roomInfoMap = {};

            response.rows.forEach(element => {
              if (element.houseNull==="空闲") {
                // 组装 roomIdOptions
                roomIdOptions.push({
                  value: element.numberId,
                  label: element.numberId
                });

                // 记录房间类型
                checkinRoomSet.add(element.roomType);

                // 组装 roomInfoMap
                roomInfoMap[element.numberId] = {
                  checkinRoom: element.roomType,
                  checkinPrice: element.roomPrice
                };
              }
            });

            // 组装 checkinRoomOptions
            const checkinRoomOptions = Array.from(checkinRoomSet).map(type => {
              return { value: type, type };
            });

            // 更新组件数据
            this.roomIdOptions = roomIdOptions;
            this.checkinRoomOptions = checkinRoomOptions;
            this.roomInfoMap = roomInfoMap;
          }
          this.loading = false;
        });
      },
      //通过房间编号出房间类型和单间金额
      handleRoomIdChange() {
        const selectedRoomId = this.form.roomId;
        const roomInfo = this.roomInfoMap[selectedRoomId];
        if (roomInfo) {
          this.form.checkinRoom = roomInfo.checkinRoom;
          this.calculateDeposit();
        } else {
          this.form.checkinRoom = null;
          this.form.checkinPrice = null;
        }
      },
      //计算金额
      calculateDeposit() {
        const selectedRoomId = this.form.roomId;
        const roomInfo = this.roomInfoMap[selectedRoomId];
        const inDays = parseInt(this.form.inDays);
        if (roomInfo &&!isNaN(inDays)) {
          this.form.checkinPrice = roomInfo.checkinPrice * inDays;
        } else {
          this.form.checkinPrice = null;
        }
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
        checkinName: undefined,
        checkinPhone: undefined,
        checkinDeposit: 100,
        reserveType: undefined,
        inDays: "1",
        houseType: undefined,
        roomId: undefined,
        checkinTime:new Date(),
        checkinType:"微信",
        CheckOutSettlement:"0",
        checkOutDetails:"无"
        // dateOut:undefined,
        // remark: undefined
      };
        this.resetForm("form");
        this.open = false;
        this.isContinueLiving=false;
        this.isCheckOut=false;
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.configId)
        this.single = selection.length!=1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加入住订单";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const numberId = row.numberId || this.ids
        getCheckInKey(numberId).then(response => {
          this.form = response.rows[0];
          this.indaysMinNumber=this.form.inDays;
          this.form.CheckOutSettlement="0";
          this.open = true;
          this.title = "编辑入住订单";
        });
      },
      //续住
      handleContinueLiving(row) {
        this.reset();
        const numberId = row.numberId || this.ids
        getCheckInKey(numberId).then(response => {
          this.form = response.rows[0];
          this.indaysMinNumber=this.form.inDays;
          this.open = true;
          this.isContinueLiving = true;
          this.title = "续住";
        });
      },
      //退房
      handleCheckOut(row) {
        this.reset();
        const configId = row.configId || this.ids
        getCheckInKey(configId).then(response => {
          this.form = response.rows[0];
          this.indaysMaxNumber=this.form.inDays;
          this.currentMonery=this.form.checkinPrice;
          this.open = true;
          this.isCheckOut=true;
          this.title = "退房";
        });
      },

      /** 提交按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.form.inDays=this.form.inDays+"";
            if (this.isCheckOut) {
              this.form.CheckOutSettlement=Number(this.form.CheckOutSettlement)||0;
              updateCheckingOut(this.form).then(response => {
                this.$modal.msgSuccess("退房成功");
                this.open = false;
                this.isCheckOut=false;
                this.getList();
              });
              return;
            }
            if (this.form.numberId != undefined) {
              updateCheckIn(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.isContinueLiving=false;
                this.getList();
              });
            } else {
              addCheckIn(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const checkinName = row.checkinName || "";
        const numberId = row.numberId || this.ids;
        this.$modal.confirm('确认删除 ' + checkinName + ' 的入住订单？').then(function() {
            return delCheckIn(numberId);
          }).then(() => {
            this.getList();
            this.$modal.msgSuccess("删除成功");
          }).catch(() => {
          });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('system/config/export', {
          ...this.queryParams
        }, `config_${new Date().getTime()}.xlsx`)
      },
      /** 刷新缓存按钮操作 */
      handleRefreshCache() {
        refreshCache().then(() => {
          this.$modal.msgSuccess("刷新成功");
        });
      }
    }
  };
  </script>
  